package cn.com.surker.material.service.impl;

import cn.com.surker.common.MessageCenterException;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.enums.material.MaterialContractTypeEnum;
import cn.com.surker.enums.system.DataBaseEnum;
import cn.com.surker.material.dao.MainMaterialDao;
import cn.com.surker.material.entity.MainMaterial;
import cn.com.surker.material.service.MainMaterialBaseService;
import cn.com.surker.oa.dao.OaMaterialDao;
import cn.com.surker.oa.entity.OaMaterial;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.vo.main.MainMaterialVO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.snaker.engine.SnakerException;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *  材料类型表
 */
@Slf4j
public abstract class MainMaterialBaseServiceImpl extends ServiceImpl<MainMaterialDao,MainMaterial> implements MainMaterialBaseService {

    @Resource
	protected MainMaterialDao mainMaterialDao;
    @Resource
    protected DataSourceInfoDao dsDao;
    @Resource
    protected OaMaterialDao oaMaterialDao;

    @Override
    public IPage<MainMaterialVO> pageMaterial(String searchVal, Long orgId,Integer type,Integer isDisplay, Integer billWeightType, Integer storeType,Integer breedType, Integer status, Integer offset, Integer limit) {
        IPage<MainMaterialVO>  resultPage = new Page<>();
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<MainMaterial> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(searchVal)){
            queryWrapper.lambda().and(p -> p.like(MainMaterial::getName, searchVal).or().like(MainMaterial::getNorms, searchVal).or().like(MainMaterial::getNameNorms, searchVal).or().like(MainMaterial::getCode,searchVal).or().like(MainMaterial::getRemark,searchVal));
        }
        if(ObjectUtil.isNotEmpty(orgId)){
            queryWrapper.lambda().eq(MainMaterial::getOrgId,orgId);
        }
        if(ObjectUtil.isNotEmpty(type)){
            queryWrapper.lambda().eq(MainMaterial::getType,type);
        }
        if(ObjectUtil.isNotEmpty(isDisplay)){
            queryWrapper.lambda().eq(MainMaterial::getIsDisplay,isDisplay);
        }
        if(ObjectUtil.isNotEmpty(billWeightType)){
            queryWrapper.lambda().eq(MainMaterial::getBillWeightType,billWeightType);
        }
        if(ObjectUtil.isNotEmpty(storeType)){
            queryWrapper.lambda().eq(MainMaterial::getStoreType,storeType);
        }
        if(ObjectUtil.isNotEmpty(breedType)){
            queryWrapper.lambda().eq(MainMaterial::getBreedType,breedType);
        }
        if(ObjectUtil.isNotEmpty(status)){
            queryWrapper.lambda().eq(MainMaterial::getStatus,status);
        }
        IPage<MainMaterial> iPage = mainMaterialDao.selectPage(new Page<>((offset + limit) /limit, limit), queryWrapper);
        BeanUtil.copyProperties(iPage,resultPage);
        /**分页插件**/
        if (ObjectUtil.isNotEmpty(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                resultPage.setTotal(pageInfo.getTotal());
            if(CollUtil.isNotEmpty(iPage.getRecords())){
                List<MainMaterial> records = iPage.getRecords();
                List<MainMaterialVO> resultRecord = new ArrayList<>();
                for (MainMaterial mainMaterial : records){
                    MainMaterialVO mainMaterialVO = BeanUtil.copyProperties(mainMaterial, MainMaterialVO.class);
                    resultRecord.add(mainMaterialVO);
                }
                resultPage.setRecords(resultRecord);
            }
        }
        return resultPage;
    }

    @Override
    public RestResultDto update(Long id, Integer type, Integer isDisplay, Integer billWeightType, Integer storeType, Integer breedType, CacheUser user) {
        MainMaterial mainMaterial = mainMaterialDao.selectById(id);
        if(mainMaterial == null || mainMaterial.getStatus() == 1){
            throw new MessageCenterException("数据不存在或已被删除");
        }
        if(StringUtils.isNull(mainMaterial.getMaterialId()) || StringUtils.isNull(mainMaterial.getOrgId()))
            throw new MessageCenterException("材料信息、公司信息不存在");
        String sql = "";
        if (!StringUtils.isNull(type) && mainMaterial.getType() != type) {
            sql += " ,type =" + type;
            mainMaterial.setType(type);
        }
        if (!StringUtils.isNull(isDisplay) && mainMaterial.getIsDisplay() != isDisplay) {
            sql += " ,is_display =" + isDisplay;
            mainMaterial.setIsDisplay(isDisplay);
        }
        if (!StringUtils.isNull(billWeightType) && mainMaterial.getBillWeightType() != billWeightType) {
            sql += " ,bill_weight_type =" + billWeightType;
            mainMaterial.setBillWeightType(billWeightType);
        }
        if (!StringUtils.isNull(storeType) && mainMaterial.getStoreType() != storeType) {
            sql += " ,store_type =" + storeType;
            mainMaterial.setStoreType(storeType);
        }
        if (!StringUtils.isNull(breedType) && mainMaterial.getBreedType() != breedType) {
            sql += " ,breed_type =" + breedType;
            mainMaterial.setBreedType(breedType);
        }
        if (StringUtils.isNull(sql) || sql.equals(""))
            throw new MessageCenterException("更新数据与原数据一致");
        Date nowDate = new Date();
        sql = "update main_material set updator='" + user.getName() + "',update_time='"
                + DateUtil.convertString(nowDate) + "' " + sql + " where material_id = "
                + mainMaterial.getMaterialId() + " and org_id = " + mainMaterial.getOrgId();
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(mainMaterial.getOrgId(), DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1)
            throw new MessageCenterException("没有变更数据");

        mainMaterial.setUpdator(user.getName());
        mainMaterial.setUpdateTime(nowDate);
        Integer code = mainMaterialDao.updateById(mainMaterial);
        if (code > 0) {
            if (ds.getType() == 0) {
                JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
                log.error("材料更新sql:" + sql);
                jdbcTemplate.update(sql);
            }
            return RestResultDto.success("更新成功");
        }
        throw new MessageCenterException("更新材料信息异常");
    }

    /**
     * 新增材料
     * @param materialId
     * @param orgId
     * @param isDisplay
     * @param billWeightType 结算类型(0:按过磅重量结算，1：按供方重量计算)
     * @param storeType 仓位类型(2:无0:筒仓1:堆场)
     * @param breedType 材料种类 MaterialBreedTypeEnum
     * @param creator
     * @param parentId
     * @return
     */
    public RestResultDto save(Long materialId, Long orgId, Integer isDisplay, Integer billWeightType,
                              Integer storeType, Integer breedType, Long parentId, String remark, String creator) {
        if(StringUtils.isNull(materialId))
            throw new MessageCenterException("材料信息不存在");
        if(StringUtils.isNull(orgId))
            throw new MessageCenterException("公司信息不存在");
        if(StringUtils.isNull(storeType))
            throw new MessageCenterException("仓位类型信息不存在");
        if(StringUtils.isNull(breedType))
            throw new MessageCenterException("材料种类信息不存在");
        if(StringUtils.isNull(isDisplay))
            isDisplay =0;
        if(StringUtils.isNull(billWeightType))
            billWeightType =0;
        OaMaterial oaMaterial = oaMaterialDao.selectById(materialId);
        if (oaMaterial == null || oaMaterial.getStatus() == 1)
            throw new MessageCenterException("材料信息不存在或已被删除");
        QueryWrapper<MainMaterial> materialQuery = new QueryWrapper<>();
        materialQuery.eq("status", 0);
        materialQuery.eq("material_id", materialId);
        materialQuery.eq("org_id", orgId);
        Integer total = mainMaterialDao.selectCount(materialQuery);
        if (total > 0)
            throw new MessageCenterException("公司材料信息已存在,请编辑修改");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId, DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1)
            throw new MessageCenterException("公司不存在或已被删除");
        Date nowDate = new Date();
        MainMaterial mainMaterial = new MainMaterial(materialId, orgId, oaMaterial.getCode(), oaMaterial.getName(),
                oaMaterial.getNorms(), oaMaterial.getFullName(), parentId, storeType, 0, remark, creator, -1, nowDate);
        mainMaterial.setBreedType(breedType);
        mainMaterial.setIsDisplay(isDisplay);
        mainMaterial.setBillWeightType(billWeightType);
        Integer code = mainMaterialDao.insert(mainMaterial);
        if (code > 0) {
            if (ds.getType() == 0) {
                JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
                String sql = "insert into  main_material (id,material_id, org_id, code, name, norms, " +
                        "name_norms, parent_id, store_type, status, remark, creator, create_time, updator, " +
                        "update_time,is_display, bill_weight_type,breed_type) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                Object[] objs = {mainMaterial.getId(), materialId, orgId, oaMaterial.getCode(), oaMaterial.getName(), oaMaterial.getNorms(),
                        oaMaterial.getFullName(), parentId, storeType, 0, remark, creator, DateUtil.convertString(nowDate), "",
                        DateUtil.convertString(nowDate), isDisplay, billWeightType, breedType};
                jdbcTemplate.update(sql, objs);
            }
            return RestResultDto.success("保存成功");
        }
        throw new MessageCenterException("报错数据异常");
    }

	@Override
	public List<MainMaterial> findList(Long orgId, Long supplierId, String types) {
		QueryWrapper<MainMaterial> query = new QueryWrapper<>();
		query.eq("status", 0);
		if (orgId != null) {
			query.eq("org_id", orgId);
		}
		if (supplierId != null) {
			query.inSql("material_id", "select material_id from main_material_contract_price where status = 0 " +
				" and supplier_id = " + supplierId + " and material_id is not null and type = " + MaterialContractTypeEnum.ZC.getCode());
		}
		if (!StringUtils.isNull(types)) {
		    String[] types_ = types.split(",");
		    query.in("type", types_);
        }
		List<MainMaterial> materialList = mainMaterialDao.selectList(query);
		return materialList;
	}

    public List<MainMaterial> findByOrg(Long orgId, Integer storageType, Long materialId) {
        QueryWrapper<MainMaterial> query = new QueryWrapper<>();
        query.eq("status", 0);
        if (orgId != null) {
            query.eq("org_id", orgId);
        }
        if (storageType != null)
            query.eq("store_type", storageType);
        if (materialId != null)
            query.inSql("store_type", "select store_type from main_material where status = 0 " +
                    " and org_id = " + orgId + " and material_id = " + materialId);
        List<MainMaterial> materialList = mainMaterialDao.selectList(query);
        return materialList;
    }

}
